<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Custom JSP tags</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, Java, web application, Custom JSP tags">
<meta name="description" content="This part of the Java EE 5 tutorials covers custom JSP tags.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>



<h1>Custom JSP tags</h1>

<p>
In this part of the JEE tutorials we will talk about custom tags. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 

<p>
A <b>custom tag</b> is a user-defined JSP language element. It is an 
extension to the JSP language. Custom tags are reusable software components. 
Custom tags are used to handle common functionality. They
also separate programming code from the content. They make the JSP pages 
look uniform. This way the JSP pages are more maintainable.
</p>

<p>
Custom tags can be created using:
</p>

<ul>
<li>Tag handlers</li>
<li>Tag files</li>
</ul>

<p>
<b>Tag handlers</b> are Java classes, that implement the custom tag. 
A <b>tag file</b> is a source file containing JSP code that is 
translated into a simple tag handler by the web container. Same as with JSPs and serlvets.
</p>

<p>
Tag handlers can be made available to a web application in two basic ways. The
classes implementing the tag handlers can be stored in an unpacked form in the
WEB-INF/classes/ subdirectory of the web application. Alternatively, if the
library is distributed as a JAR, it is stored in the WEB-INF/lib/ directory of the
web application.
</p>


<h2>Empty custom tag</h2>


<p>
When we started with JavaServer pages, we introduced a simple example, that showed 
the current date. In the following
example, we put the java code into the tag handler and thus, separate the code 
from the content.
</p>

<p>
Each custom tag implemented with a tag handler must be declared in a special 
xml file called <b>tag library descriptor</b>
<b>(TLD)</b>. The TLD file maps custom tags to their corresponding simple 
tag handler implementation classes. 
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@taglib prefix="d" uri="http://zetcode.com/tlds/date" %&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Custom tags&lt;/title&gt;
        &lt;style&gt;
        * { font-size: 12px; font-family: Verdana }
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h2&gt;Date&lt;/h2&gt;
        &lt;b&gt;Today's Date: &lt;/b&gt; &lt;d:DateTag /&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
This is the jsp file, that will output the current date. 
</p>

<pre class="explanation">
&lt;%@taglib prefix="d" uri="http://zetcode.com/tlds/date" %&gt;
</pre>

<p>
The <b>taglib</b> directive will enable us to use the custom 
tag in this jsp page. The <b>uri</b> parameter is a unique 
identifier for the tag library. In the previous versions of the 
JSP technology, developers had to edit the <b>web.xml</b> 
file. Today this is not necessary. The container will automatically map the 
uri with the coresponding TLD. The uri must be unique within the application.
The taglib directive also specifies the prefix, used in our custom tag.
</p>

<pre class="explanation">
&lt;b&gt;Today's Date: &lt;/b&gt; &lt;d:DateTag /&gt;
</pre>

<p>
Here we use our custom tag. This tag displays current date and time. 
The <code>DateTag</code> is the
name of the custom tag, specified in the date.tld file. We have a tag 
with empty body, so there is ending tag. 
</p>

<div class="codehead">date.tld</div>
<pre class="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;taglib&gt;
  &lt;tlib-version&gt;1.0&lt;/tlib-version&gt;
  &lt;jsp-version&gt;2.0&lt;/jsp-version&gt;
  &lt;short-name&gt;d&lt;/short-name&gt;
  &lt;uri&gt;http://zetcode.com/tlds/date&lt;/uri&gt;

  &lt;tag&gt;
    &lt;name&gt;DateTag&lt;/name&gt;
    &lt;tag-class&gt;com.zetcode.DateTagHandler&lt;/tag-class&gt;
    &lt;body-content&gt;empty&lt;/body-content&gt;
  &lt;/tag&gt;

&lt;/taglib&gt;
</pre>

<p>
This is the tag library descritor, for our example. In the 
<b>tag</b> element, we provide the name of the tag, the 
Java class, that implements the tag. We also specify, that our tag has no body.
We placed the date.tld file into the <b>WEB-INF/tlds</b> directory.
</p>


<div class="codehead">DateTagHandler.java</div>
<pre class="code">
package com.zetcode;

import java.util.Date;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;


public class DateTagHandler extends SimpleTagSupport {

  public void doTag() throws JspException {

      JspWriter out=getJspContext().getOut();

      try {

          out.println(new Date());

      } catch (java.io.IOException ex) {
          throw new JspException(ex.getMessage());
      }
  }
}
</pre>

<p>
This is the implementation of the tag halder for our custom tag. 
</p>


<pre class="explanation">
out.println(new Date());
</pre>

<p>
We print the current date.
</p>

<img src="/img/java/jee/customtag.png" alt="An custom tag">
<div class="figure">Figure: A custom tag</div>


<h2>Tag file</h2>

<p>
The other way of creating custom tags is using the tag files. The idea is 
identical to how jsp files are 
transformed to servlets. Similarly, the tag files are first transformed 
into the tag handlers. And then compiled. 
</p>

<p>
In the next example, we will use custom tags to indicate mandatory and non 
mandatory fields in a html form.
Our custom tag will also have an attribute. 
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@taglib prefix="t" tagdir="/WEB-INF/tags" %&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Tag File&lt;/title&gt;
    &lt;style&gt;
        * { font-size: 12px; font-family: Verdana }
        input, textarea { border: 1px solid #ccc }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;  

   &lt;div style="width:400px"&gt;
   &lt;center&gt;
   &lt;form&gt;   
     &lt;table&gt;
       &lt;tr&gt;
         &lt;td&gt;&lt;t:field text="Name" mandatory="yes" /&gt;&lt;/td&gt;
         &lt;td&gt;&lt;input type="text" name="from"&gt;&lt;/td&gt;
       &lt;/tr&gt;
       &lt;tr&gt;
       &lt;tr&gt;
         &lt;td&gt;&lt;t:field text="Email" mandatory="no" /&gt;&lt;/td&gt;
         &lt;td&gt;&lt;input type="text" name="to"&gt;&lt;/td&gt;
       &lt;/tr&gt;
       &lt;tr&gt;
         &lt;td&gt;&lt;t:field text="Message" mandatory="yes" /&gt;&lt;/td&gt;
         &lt;td&gt;&lt;textarea cols="25" rows="8" name="message"&gt;&lt;/textarea&gt;&lt;/td&gt;
       &lt;/tr&gt;
   &lt;/table&gt;
   &lt;br&gt;
   &lt;input type="submit" value="submit"&gt;
   &lt;/form&gt;
   &lt;/center&gt;
   &lt;/div&gt;
  &lt;/body&gt;
&lt;/html>
</pre>

<p>
This is the jsp file, where we use our custom tag. 
</p>


<pre class="explanation">
&lt;%@taglib prefix="t" tagdir="/WEB-INF/tags" %&gt;
</pre>

<p>
The prefix attribute defines the prefix that distinguishes tags defined by a given tag library
from  other tag libraries.
The tagdir attribute identifies the location of the tag library. 
The value of the attribute must start with /WEB-INF/tags/
</p>


<pre class="explanation">
&lt;td&gt;&lt;t:field text="Name" mandatory="yes" /&gt;&lt;/td&gt;
</pre>

<p>
The custom tag creates a text field in the html form. It is a mandatory 
field, so we will see an asterix.
</p>

<div class="codehead">field.tag</div>
<pre class="code">
&lt;%@tag description="normal or mandatory fields" pageEncoding="UTF-8"%&gt;


&lt;%@attribute name="mandatory" required="true"%&gt;
&lt;%@attribute name="text" required="true"%&gt;


&lt;%
  if ("yes".equals(mandatory)) {
      out.println(text + "*");
  } else {
      out.println(text);
  }
%&gt;
</pre>

<p>
The tag fiel field.tag is created using the jsp syntax. 
We placed the field.tag file into the <b>WEB-INF/tags</b> directory.
If a tag is implemented as a tag file and ispackaged in WEB-INF/tags/ or a subdirectory, 
a TLD will be generated automatically by the web container.
</p>

<img src="/img/java/jee/tagfilehier.png" alt="TagFile project">
<div class="figure">Figure: TagFile project</div>


<pre class="explanation">
&lt;%@attribute name="mandatory" required="true"%&gt;
</pre>

<p>
This directive creates an attribute for our custom tag. The attribute name 
is mandatory and it is not optional.
We must provide it, when we use the custom tag. 
</p>

<pre class="explanation">
if ("yes".equals(mandatory)) {
    out.println(text + "*");
} else {
    out.println(text);
}
</pre>

<p>
Mandatory fields will have an asterix. 
</p>

<img src="/img/java/jee/tagfile.png" alt="A tag file">
<div class="figure">Figure: TagFile</div>



<h2>Random numbers</h2>

<p>
If we need a custom tag, we might look, if it wasn't already created by someone.
Say we want to generate random numbers using custom tags. There is 
already a library to achieve this. 
The random tag library from the Jakarta Project. From their web 
<a href="http://jakarta.apache.org/taglibs/">http://jakarta.apache.org/taglibs/</a> , 
we download the latest random tag library. The name of the jar is <b>taglibs-random.jar</b>. 
We put the jar file into the <b>WEB-INF/lib</b> directory.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;%@ taglib uri="http://jakarta.apache.org/taglibs/random-1.0" prefix="rand" %&gt;

&lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;Random&lt;/title&gt;
      &lt;style&gt;
          * { font-size: 12px; font-family: Verdana }    
      &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;h2&gt;Random numbers&lt;/h2&gt;
  &lt;/body&gt;

  &lt;% for (int i = 0; i &lt; 100; i++) {%&gt;

  &lt;% if (i % 10 == 0) {
       out.println("&lt;br&gt;");
  } %&gt;

  &lt;rand:number id="random1" range="1-100"/&gt;
  &lt;jsp:getProperty name="random1" property="random"/&gt; &nbsp;

  &lt;% } %&gt;

&lt;/html>
</pre>

<p>
In this example, we display 100 random numbers. 
</p>

<pre class="explanation">
&lt;%@ taglib uri="http://jakarta.apache.org/taglibs/random-1.0" prefix="rand" %&gt;
</pre>

<p>
We declare, that we use the random tag library in our jsp page. The uri is a unique 
identifier for the tag library. The container tries to match it against any &lt;taglib-uri&gt; 
elements in the application’s web.xml file or the &lt;uri&gt; element of TLDs in JAR files 
in /WEB-INF/lib/ or TLDs under WEB-INF.
</p>

<p>
In our case, the Resin AS will look inside the taglibs-random.jar at 
the META-INF/tablib.tld file for the uri.
</p>

<pre class="code">
&lt;taglib&gt;
  &lt;taglib-uri&gt;
    http://jakarta.apache.org/taglibs/random-1.0
  &lt;taglib-uri&gt;
  &lt;taglib-location&gt;
    /WEB-INF/tlds/taglibs-random.tld
  &lt;taglib-location&gt;
&lt;/taglib&gt;
</pre>

<p>
For older containers, we must edit the web.xml file. We must provide the uri and the taglib location. 
For newer containers, we need not to copy the taglibs-random.tld. The TLD is already 
available in the jar file and the contaner will look it up automatically.
</p>


<pre class="explanation">
&lt;rand:number id="random1" range="1-100"/&gt;
&lt;jsp:getProperty name="random1" property="random"/&gt; &nbsp;
</pre>

<p>
Here we create and display a random number in range from 1 .. 100.
</p>


<p>
In this chapter we have described custom JSP tags. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified February 5, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

